package com.one.common.manager;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;

import java.util.Stack;

/**
 * Author：zhulunjun
 * Time：2017/9/16
 * description：activity管理
 */

public class ActivityPageManager {
    private static Stack<Activity> activityStack;
    private static ActivityPageManager instance;

    private ActivityPageManager() {
    }

    public static ActivityPageManager getAppManager() {
        if (instance == null) {
            instance = new ActivityPageManager();
        }
        return instance;
    }

    public void addActivity(Activity activity) {
        if (activityStack == null) {
            activityStack = new Stack<Activity>();
        }
        if(activity!=null)
            activityStack.add(activity);
    }

    public Activity currentActivity() {
        if (!activityStack.isEmpty()) {
            return activityStack.lastElement();
        }
        return null;
    }

    public void removeActivity(Activity activity) {
        if (activityStack == null) {
            activityStack = new Stack<Activity>();
        }
        if(activity!=null)
            activityStack.remove(activity);
    }
    public void finishAllActivity() {
        for (int i = 0, size = activityStack.size(); i < size; i++) {
            if (null != activityStack.get(i)) {
                activityStack.get(i).finish();
            }
        }
        activityStack.clear();
    }

    public void AppExit(Context context) {
        try {
            finishAllActivity();
            ActivityManager activityMgr = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            activityMgr.restartPackage(context.getPackageName());
            System.exit(0);
        } catch (Exception e) {

        }
    }

    /**
     * 获取栈顶的activity
     */
    public Activity getTopActivity(){
        return activityStack.lastElement();
    }
}
